Strobogrammatic Number II

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Find all strobogrammatic numbers that are of length = n.

For example,

Given n = 2, return ["11","69","88","96"].

Hint:

Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.

Solution:

  1. public class Solution {
  2. public List<String> findStrobogrammatic(int n) {
  3. return helper(n, n);
  4. }
  5. List<String> helper(int n, int m) {
  6. if (n == 0) return new ArrayList<String>(Arrays.asList(""));
  7. if (n == 1) return new ArrayList<String>(Arrays.asList("0", "1", "8"));
  8. List<String> list = helper(n - 2, m);
  9. List<String> res = new ArrayList<String>();
  10. for (int i = 0; i < list.size(); i++) {
  11. String s = list.get(i);
  12. if (n != m) res.add("0" + s + "0");
  13. res.add("1" + s + "1");
  14. res.add("6" + s + "9");
  15. res.add("8" + s + "8");
  16. res.add("9" + s + "6");
  17. }
  18. return res;
  19. }
  20. }